package com.laxia.util;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author weishuai
 */
public class CollectionUtil {

    private CollectionUtil() {
    }

    public static boolean isEmpty(Collection<? extends Object> col) {
        return col == null || col.isEmpty();
    }

    public static boolean isNotEmpty(Collection<? extends Object> col) {
        return col != null && col.size() > 0;
    }

    public static boolean isEmpty(Map<? extends Object, ? extends Object> map) {
        return map == null || map.isEmpty();
    }

    public static boolean isNotEmpty(Map<? extends Object, ? extends Object> map) {
        return map != null && map.size() > 0;
    }

    /**
     * 注意：如果list里是复杂对象 需要重写其equals方法
     */
    public static <T> boolean isEqualList(List<T> list1, List<T> list2) {
        return isEqualList(list1, list2, false);
    }

    /**
     * @param ordered 是否比对位置（严格比对）
     */
    public static <T> boolean isEqualList(List<T> list1, List<T> list2, boolean ordered) {
        if (isEmpty(list1) && isEmpty(list2)) {
            return true;
        }
        if (list1 == null || list2 == null || list1.size() != list2.size()) {
            return false;
        }
        if (ordered) {
            for (int i = 0; i < list1.size(); i++) {
                if (!list1.get(i).equals(list2.get(i))) {
                    return false;
                }
            }
        } else {
            HashSet<T> set1 = new HashSet<>(list1);
            HashSet<T> set2 = new HashSet<>(list2);
            if (set1.size() != set2.size()) {
                return false;
            }
            return set1.containsAll(set2);
        }

        return true;
    }

    /**
     * @param data  list数据
     * @param start 切割startIndex 从0开始
     * @param size  切割长度
     */
    public static <T> List<T> subList(List<T> data, int start, int size) {
        if (data == null || data.isEmpty() || data.size() < start) {
            return Collections.emptyList();
        }
        start = Math.max(start, 0);
        int toIndex = Math.min((start + size), data.size());

        return data.subList(start, toIndex);
    }

    public static boolean eqAnyOne(List<Integer> data1, List<Integer> data2) {
        if (isEmpty(data1) || isEmpty(data2)) {
            return false;
        }
        return data1.stream().anyMatch(data2::contains);
    }

    public static String toString(Collection<?> numbers) {
        if (isEmpty(numbers)) {
            return "";
        }
        return numbers.stream().map(Object::toString).collect(Collectors.joining(","));
    }
}
